﻿using System;
using System.Collections.Generic;

namespace MAF.UserSecurity
{
    [Serializable]
    public class ActiveUserCollection
    {
        /// <summary>
        /// 活动用户缓存
        /// </summary>
        private static Dictionary<Guid, UserContext> _Users;
        
        /// <summary>
        /// 构造方法
        /// </summary>
        public ActiveUserCollection()
        {
            _Users = new Dictionary<Guid, UserContext>();
        }

        #region 集合操作

        /// <summary>
        /// 索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public UserContext this[Guid index]
        {
            get
            {
                if (_Users.ContainsKey(index))
                    return _Users[index];
                else
                    return null;
            }
        }

        /// <summary>
        /// 增加活动用户
        /// </summary>
        /// <param name="user"></param>
        public void Add(Guid token, UserContext user)
        {
            if (_Users.ContainsKey(token))
            {
                Remove(token);
            }
            _Users.Add(token,user);
        }

        /// <summary>
        /// 移除活动用户
        /// </summary>
        /// <param name="user"></param>
        public void Remove(Guid token)
        {
            _Users.Remove(token);
        }

        /// <summary>
        /// 自动清理过期的用户
        /// </summary>
        protected void AutoClear()
        {

        }

        #region 转换为其他类型集合

        /// <summary>
        /// 转换为词典对象
        /// </summary>
        /// <returns></returns>
        public Dictionary<Guid, UserContext> ToDictionary()
        {
            return _Users;
        }

        /// <summary>
        /// 转换为List
        /// </summary>
        /// <returns></returns>
        public List<UserContext> ToList()
        {
            List<UserContext> users = new List<UserContext>();
            foreach (KeyValuePair<Guid, UserContext> kvp in _Users)
            {
                users.Add(kvp.Value);
            }
            return users;
        }

        /// <summary>
        /// 转换为数组
        /// </summary>
        /// <returns></returns>
        public UserContext[] ToArray()
        {
            return ToList().ToArray();
        }

        #endregion

        #endregion
    }
}
